#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: funcs.py
@contact: zwb15083976291@163.com
@time: 2021/10/10
"""


def query_dict_to_dict(query_dict: 'query_dict', *keys: "query_dict keys", constrains: dict = None) -> dict:
    """
    将查询字典转换字典
    """
    if keys and constrains:
        assert 0, 'keys 和 constrains 只能设置一个'
    if keys:
        return_dict = {}
        for key in keys:
            query_dict_value = query_dict.get(key)
            if type(query_dict_value) == str:  # 字符串要去除空格,检测空字符串,全部转换为None
                query_dict_value = query_dict_value.strip() if query_dict_value.strip() else None
                query_dict_value = '' if query_dict_value == 'delete' else query_dict_value  # 删除字段置为空
                return_dict[key] = query_dict_value
                # keys[key]['allow_blank'] = True
            elif query_dict_value is None:  # 如果没有传,直接使用None
                return_dict[key] = None
            else:
                return_dict[key] = query_dict_value  # 其他值直接使用

        return return_dict
    if constrains:
        return_dict = {}
        for key in constrains:
            query_dict_value = query_dict.get(key)
            if type(query_dict_value) == str:  # 字符串要去除空格,检测空字符串,全部转换为None
                query_dict_value = query_dict_value.strip() if query_dict_value.strip() else None
                return_dict[key] = query_dict_value or constrains[key].get('default')  #
                return_dict[key] = '' if query_dict_value == 'delete' else return_dict[key]  # 删除字段置为空
                # constrains[key]['allow_blank'] = True
            elif query_dict_value is None:  # 如果没有传,直接使用默认值
                return_dict[key] = constrains[key].get('default')
            else:
                return_dict[key] = query_dict_value  # 其他值直接使用

        return return_dict


def generate_deserial_constrains(required: 'iterable' = [], optional: "iterable" = [], defualt_value: dict = {}):
    """生成反序列化验证条件"""
    constrains = {ele: dict(required=True, allow_null=False, allow_blank=False, allow_empty=False) for ele in required}
    constrains.update(
        {ele: dict(required=False, allow_null=True, allow_blank=True, allow_empty=True) for ele in optional})
    for key in defualt_value:
        if key in constrains:
            constrains[key]['default'] = defualt_value.get(key)

    return constrains


def get_dict_error_info(error_dict: dict):
    """获取错误字典中的异常信息"""
    for idx, value in error_dict.items():
        try:
            error_key = ''
            error_key = error_dict.serializer.fields.get(idx).label
            return '{}错误--{}'.format(error_key, value[0])
        except (NameError, AttributeError, KeyError) as e:
            if isinstance(value, list):
                value = value[0]
            if isinstance(value, dict):
                value = list(value.values())[0]
            info = '{}错误--{}'.format(error_key, value[0]) if error_key else value
            return info
